
#include "gpio-driver.h"

int RegitsterGpio(int pin)
{
    FILE *export_file = fopen("/sys/class/gpio/export", "w");
    if (export_file == NULL) {
        perror("Failed to open GPIO export file");
        return -1;
    }
    fprintf(export_file, "%d", pin);
    fclose(export_file);
    return 0;
}

int SetDirection(int pin, char *direction)
{
    char direction_path[50];
    snprintf(direction_path, sizeof(direction_path), "/sys/class/gpio/gpio%d/direction", pin);
    FILE *direction_file = fopen(direction_path, "w");
    if (direction_file == NULL) {
        perror("Failed to open GPIO direction file");
        return -1;
    }
    fprintf(direction_file, direction);
    fclose(direction_file);
    return 0;
}


int SetValue(int pin, int value)
{
    char value_path[50];
    char cat_command[100];
    snprintf(value_path, sizeof(value_path), "/sys/class/gpio/gpio%d/value", pin);
    FILE *value_file = fopen(value_path, "w");
    if (value_file == NULL) {
        perror("Failed to open GPIO value file");
        return -1;
    }
    fprintf(value_file, "%d",value);
    fflush(value_file);
    fclose(value_file);
    return 0;
}

int GetValue(int pin, int *value)
{
    char value_path[50];
    char cat_command[100];
    snprintf(value_path, sizeof(value_path), "/sys/class/gpio/gpio%d/value", pin);
    FILE *value_file = fopen(value_path, "r");
    if (value_file == NULL) {
        perror("Failed to open GPIO value file");
        return -1;
    }
    fscanf(value_file, "%d", value);
    fclose(value_file);
    return 0;
}


int UnregisterGpio(int pin)
{
    FILE *unexport_file = fopen("/sys/class/gpio/unexport", "w");
    if (unexport_file == NULL) {
        perror("Failed to open GPIO unexport file");
        return -1;
    }
    fprintf(unexport_file, "%d", pin);
    fclose(unexport_file);
    return 0;
}

/*
int main(int argc, char *argv[])
{
    int Pin_DC   = 32;
    int Pin_RST  = 33;

    RegitsterGpio(Pin_DC);
    RegitsterGpio(Pin_RST);
    SetDirection(Pin_DC, "out");
    SetDirection(Pin_RST, "in");

    int value;
    for(int i=0; i<10; i++)
    {
        SetValue(Pin_DC, 1);
        GetValue(Pin_RST, &value);
        printf("Pin_RST value is %d\n", value);
        sleep(1);

        SetValue(Pin_DC, 0);
        GetValue(Pin_RST, &value);
        printf("Pin_RST value is %d\n", value);
        sleep(1);
    }
    UnregisterGpio(Pin_DC);
    UnregisterGpio(Pin_RST);
    return 0;
}
*/
